package org.hry.netty.listeners;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.hry.netty.heartbeat.HeartBeatClientInitializer;

import java.util.concurrent.TimeUnit;

/**
 * @Desc
 * @Author houruiyang
 * @Date 2021/7/20
 **/
public class ReconnectClient {
    EventLoopGroup worker = new NioEventLoopGroup();


    public static void main(String[] args) {
        ReconnectClient client = new ReconnectClient();
        client.start();

    }

    public void start() {
        try {
            Bootstrap client = new Bootstrap();
            client.group(worker).channel(NioSocketChannel.class).handler(new HeartBeatClientInitializer());
            Channel channel = client.connect("localhost", 9999).addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    System.out.println("success");
                } else {
                    System.out.println("fail");
                    TimeUnit.SECONDS.sleep(2);
                    start();
                }
            }).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            System.out.println("异常了");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
            start();
        } finally {
            worker.shutdownGracefully();
        }
    }


    public void shutDown() {
        worker.shutdownGracefully();
    }


}
